package com.flyxiaozhu.erp.admin.configurations;

import com.flyxiaozhu.erp.admin.authorize.PermissionManager;
import com.flyxiaozhu.erp.core.annotations.StockRule;
import com.flyxiaozhu.erp.core.libs.StockFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AppListener implements ApplicationListener<ContextRefreshedEvent> {

    private PermissionManager permissionManager;

    @Autowired
    void setPermissionManager(PermissionManager permissionManager) {
        this.permissionManager = permissionManager;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            try {
                initPermission();
                initAutoDelivery(event);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initPermission() {
        permissionManager.init();
    }

    /**
     * 加载发货规则
     *
     * @param event
     * @throws Exception
     */
    private void initAutoDelivery(ContextRefreshedEvent event) throws Exception {
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(StockRule.class);
        StockFactory.init(beans);
    }
}
